package servlets.local;

import hibernate.method.TableEntityMethods;
import hibernate.model.TableEntity;
import hibernate.util.HibernateUtil;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.json.JSONException;
import org.json.JSONObject;

/**
 * Servlet implementation class tableDetails
 */
@WebServlet("/tableDetails")
public class tableDetails extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public tableDetails() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		String req = request.getParameter("table_id");
		System.out.println(req);
		int table_id = Integer.parseInt(req);
		response.setContentType("text/plain");
		SessionFactory sessionFactory = HibernateUtil
				.getSessionAnnotationFactory();
		Session s = sessionFactory.openSession();
		s.beginTransaction();
		TableEntityMethods tem = new TableEntityMethods();
		TableEntity te = tem.getTableById(sessionFactory, s, table_id);
		
		JSONObject json = new JSONObject();
		PrintWriter out = response.getWriter();
		try {
			json.put("valueTable", te.getValue());
			json.put("labelTable", te.getLabel());
			json.put("personsTable", te.getPersons());
			json.put("smokingTable", te.getSmoking());
			json.put("idTable", te.getTable_id());
			json.put("localTable", te.getLocal_id());
		} catch (JSONException e) {
			e.printStackTrace();
		}
		out.println(json);
		out.flush();

		s.getTransaction().commit();
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

}
